<template>
    <div>
        <el-upload class="upload-demo" ref="upload" accept=".csv,.CSV" action="" :multiple="false" :limit="1" :auto-upload="false" :show-file-list="false" :on-change="changeFile">
            <div class="editdata">选择csv文件</div>
        </el-upload>
    </div>
</template>

<script>
import Papa from 'papaparse';
import message from '@/js/util/message.js';

export default {
    name: 'UploadCsv',
    props: {
        value: {
            default: () => [],
            type: Array
        },
        mode: {
            default: '0',
            type: String
        }
    },
    data() {
        return {};
    },
    methods: {
        changeFile(file) {
            this.$refs.upload.clearFiles();
            //每次上传前都清空
            this.file = {};
            //赋值
            if (file.status !== 'ready') return;
            let newfile = file.raw;
            let fReader = new FileReader();
            let me = this;
            fReader.onload = function(evt) {
                // 将csv转换成二维数组
                Papa.parse(newfile, {
                    encoding: 'GBK',
                    complete: (res) => {
                        // UTF8 \r\n与\n混用时有可能会出问题
                        let data = res.data;
                        if (data[data.length - 1] == '') {
                            //去除最后的空行
                            data.pop();
                        }
                        for (let index = 0; index < data.length; index++) {
                            data[index] = data[index].filter(Boolean);
                        }
                        me.completeEdit(data);
                    }
                });
            };
            fReader.readAsText(newfile, 'GBK'); // utf-8 GB2312  GBK
        },
        completeEdit(data) {
            if ((this.mode === '1' || this.mode === '2') && data[0].length !== this.value[0].length) {
                message.message('导入格式跟提供的样例数据不一致，请重新编辑之后在上传', 'warning');
                return false;
            }
            this.close(data);
        },
        /* 关闭数据弹框 */
        close(data) {
            message.message('导入成功', 'success');
            this.$emit('success', data);
        }
    }
};
</script>
<style lang="scss">
.upload-demo {
    .el-upload {
        width: 100%;
    }
}
</style>
<style lang="scss" scoped>
.editdata {
    margin-top: 10px;
    height: 30px;
    line-height: 30px;
    background: #ffffff0f;
    color: $FontWhite;
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    &:hover {
        background: #ffffff33;
    }
}
</style>